﻿/// <summary>
/// https://leetcode-cn.com/problems/string-to-integer-atoi/
/// </summary>
public class Solution
{
    private string ScanNumber(string s)
    {
        bool started = false;
        System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
        foreach (var c in s.TrimStart())
        {
            if (c is '-' or '+')
            {
                if (started)
                    break;
                else
                {
                    started = true;
                    _ = stringBuilder.Append(c);
                    continue;
                }
            }

            if (c is <= '9' and >= '0')
            {
                started = true;
                _ = stringBuilder.Append(c);
                continue;
            }

            break;
        }
        return stringBuilder.ToString();
    }

    private int CutBig(System.Numerics.BigInteger b)
    {
        if (b < int.MinValue)
            return int.MinValue;
        if (b > int.MaxValue)
            return int.MaxValue;
        return (int)b;
    }

    public int MyAtoi(string s)
    {
        s = this.ScanNumber(s);
        return System.Numerics.BigInteger.TryParse(s, out var result) ? this.CutBig(result) : 0;
    }
}